package com.xlf.book.servlet;

import com.xlf.book.biz.BookInfoBiz;
import com.xlf.book.biz.impl.BookInfoBizImpl;
import com.xlf.book.po.BookInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xie'lin'feng
 * @date 2020-07-22-11:57
 * @description 新增处理器
 */
@WebServlet("/add")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        BookInfoBiz bib = new BookInfoBizImpl();
        String bookName = req.getParameter("bookName");
        Double price = Double.valueOf(req.getParameter("price"));
        Integer typeId = Integer.valueOf(req.getParameter("type"));
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = sdf.parse(req.getParameter("bornDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String imgUrl = req.getParameter("imgUrl");
        Integer state = Integer.valueOf(req.getParameter("state"));
        BookInfo info = new BookInfo(null,bookName,price,typeId,date,imgUrl,state);
        boolean result = bib.addInfo(info);
        if (result){
            resp.sendRedirect("getAll");
        }else {
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('新增失败!');location.href='getAll';</script>");
            out.flush();
            out.close();
        }
    }
}
